<?php
namespace Permission\Behaviors;
class PermissionBehavior extends \Think\Behavior{

    //权限检测入口
    public function run(&$param){
        // G('begin');
        $permission_condition = [
            'perms' => strtolower(MODULE_NAME.'.'.CONTROLLER_NAME.'.'.ACTION_NAME),
            'type' => ['neq','M'] //权限菜单类型不能等于M，M为目录
        ];
        // 先检测是否是被管控的权限
        $m = D('PermissionMenu');
        $check_permission = $m->where($permission_condition)->field('id,type')->find(); //只读取第一行
        if($check_permission){
            if($_SESSION['loginUser'] || $_REQUEST['current_uid']){
                $uid = $_SESSION['loginUser'] ? $_SESSION['loginUser']['id'] : $_REQUEST['current_uid'];
                //直接写sql连表查询
                $sql  = 'select A.* from mini_permission_role_menu A left join mini_permission_role B on A.role_id = B.id left join mini_users C on B.name = C.role ';
                $sql .= 'where C.id = '.$uid.' and A.menu_id = '.$check_permission['id'].' limit 1';
                $check = $m->query($sql);
                if(!$check){
                    if($check_permission['type'] == 'A'){
                        _apiReturn(0,'没有权限');
                    }else{
                        redirect('/404.html');
                    }
                }
            }else{
                if($check_permission['type'] == 'A'){
                    _apiReturn(0,'检测不到用户，无访问权限~');
                }else{
                    redirect('/404.html');
                }
            }
        }
        // G('end');
        // echo G('begin','end').'s';
    }
}